package com.sun.test.controller;

import com.sun.test.dao.UserDao;
import com.sun.test.domain.User;
import com.sun.test.dto.RedisBaseRequest;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author zhangquanwei
 * @version 1.0
 * @date 2024-12-18 16:27
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserDao userDao;


    @PostMapping("/set")
    public Boolean set(@RequestBody RedisBaseRequest req) {
        stringRedisTemplate.opsForValue().set(req.getKey(), req.getValue());
        return true;
    }

    @PostMapping("/get")
    public String get(@RequestBody RedisBaseRequest req) {
        return stringRedisTemplate.opsForValue().get(req.getKey());
    }

    @PostMapping("/setUser")
    public Boolean setUser(@RequestBody RedisBaseRequest req) {
        User user = userDao.getByUserId(req.getKey());
        Optional.ofNullable(user).orElseThrow(RuntimeException::new);
        redisTemplate.opsForValue().set(req.getKey(), user);
        return true;
    }

    @PostMapping("/getUser")
    public User getUser(@RequestBody RedisBaseRequest req) {
        return  (User) redisTemplate.opsForValue().get(req.getKey());
    }
}
